package com.athena.view 
{
	import com.adobe.serialization.json.JSON;
	import com.athena.Objects.PlayerObject;
	import com.athena.ui.board;
	import com.athena.utils.Delegate;
	import com.athena.utils.Util;
	import com.cubeia.firebase.io.protocol.LeaveRequestPacket;
	import com.greensock.TweenMax;
	import com.junkbyte.console.Cc;
	import flash.events.DataEvent;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.geom.Point;
	import flash.utils.Timer;
	/**
	 * ...
	 * @author chau
	 */
	public class GameBoard extends board
	{
		private var _tableid : int;
		private var _mark : int;
		private var _arrPlayer : Array = [];
		private var _view : Boolean;
		private var isCreate : Boolean;
		private var started : Boolean = false;
		private var currCardScaleX : Number = 60 / 38;
		private var currCardScaleY : Number = 82 / 52;
		
		private var cardDuoiBanScaleX : Number = 1;
		private var cardDuoiBanScaleY : Number = 1;
		
		private var turnOfPlayer : String;
		
		private var tChiaBai : Timer;
		private var arrChiaBai : Array = [];
		private var finishChia : Boolean = false;
		private var targetCard : Card;
		private var arrCardPoint : Array = [new Point(345.95, 398.35), new Point(819, 185), new Point(374, 125), new Point(164, 185)];
		private var direction : Array = [new Point(24, 0), new Point(0, 15), new Point(19, 0), new Point(0, 15)];
		
		public function GameBoard(str : String, _v : Boolean = false, _cr : Boolean = false) {
			_view = _v;
			isCreate = _cr;
			addEvent();
			displayUi(str);
		}
		
		private function sendReady(e : MouseEvent) : void {
			var obj:Object = new Object();
			obj.evt = "rtable";
			Main.getInstance().socket.sendData(JSON.encode(obj));
		}
		private function sendStart(e : MouseEvent) : void {
			//var avt : avatar = getAvatarByName(ASLieng.currPlayer.PlayerName);
			//if (avt != null) avt.stopTimeTurn();
			var ob:Object = new Object();
			ob.evt = "sgame";
			Main.getInstance().socket.sendData(JSON.encode(ob));
		}
		public function reset(str : String, _v : Boolean = false, _cr : Boolean = false) : void {
			_arrPlayer = [];
			_view = _v;
			isCreate = _cr;
			while (player_mc.numChildren > 0) {
				var _avt : avatar = avatar(player_mc.getChildAt(0));
				_avt.removeEvent();
				player_mc.removeChild(_avt); _avt = null;
			}
			addEvent();
			displayUi(str);
		}
		private function displayUi(str : String) : void {
			try {
				var obj : Object = JSON.decode(str);
				_tableid = obj.Id;
				_mark = obj.M;
				var _arr : Array = obj.ArrP as Array;
				for each(var _o : Object in _arr) {
					if (_o.N == Main.getInstance().currPlayer.displayName) {
						Main.getInstance().currPlayer.ip = _o.sIP;
						Main.getInstance().currPlayer.ready = _o.isStart;
						_arrPlayer.push(Main.getInstance().currPlayer);
						continue;
					}
					var pl : PlayerObject = new PlayerObject();
					pl.displayName = _o.N;
					pl.mark = _o.AG;
					pl.ip = _o.sIP;
					pl.ready = _o.isStart;
					_arrPlayer.push(pl);
				}
				id_txt.htmlText = "<font color='#FFFFFF'>Bàn </font><font color='#FFFF00'>" + _tableid + "</font>";
				cuoc_txt.htmlText = "<font color='#FFFFFF'>Cược </font><font color='#FFFF00'>" + _mark + "</font>";
				for each(var _pl : PlayerObject in _arrPlayer) {
					var _p : int = getPositionPlayer(_pl.displayName);
					var _avt : avatar = new avatar(_p, _pl.displayName, _pl.vip, _pl.mark);
					player_mc.addChild(_avt);
				}
				if (_view) {
					ready_btn.visible = false;
				}
				if (isCreate) {
					ready_btn.visible = false;
					Main.getInstance().currPlayer.ready = true;
					var _av : avatar = getAvatarByName(Main.getInstance().currPlayer.displayName);
					if (_av) _av.setReady(true);
				}
				begin_btn.visible = false;
				
				xepbai_btn.visible = false;
				danhbai_btn.visible = false;
				boluot_btn.visible = false;
				bochon_btn.visible = false;
				
				
			}catch(err : Error) {Cc.error(err + " displayUi")}
		}
		
		public function otherJoinTable(str : String) : void {
			if (!started) {
				var obj : Object = JSON.decode(str);
				var pl : PlayerObject = new PlayerObject();
				pl.ready = obj.isStart;
				pl.displayName = obj.N;
				pl.ip = obj.sIP;
				pl.vip = obj.VIP;
				pl.mark = obj.AG;
				_arrPlayer.push(pl);
				var _p : int = getPositionPlayer(pl.displayName);
				var avt :avatar = new avatar(_p, pl.displayName, pl.vip, pl.mark);
				player_mc.addChild(avt);
			}else {
				_arrPlayer.push(pl);
			}
			
		}
		
		public function startGame(obj : Object) : void {
			if (isCreate) begin_btn.visible = false;
			started = true;
			
			while (card_mc.numChildren > 0) {
				var _c : Card = Card(card_mc.getChildAt(0));
				_c.removeEvent();
				card_mc.removeChild(_c); _c = null;
			}
			dealCard(obj);
		}
		private function dealCard(obj : Object) : void {
			try {
				arrChiaBai = [];
				finishChia = false;
				for (var j : int = 0 ; j < _arrPlayer.length; j++ ) {
					(_arrPlayer[j] as PlayerObject).arrCard = [];
				}
				var arrCard : Array = obj.Arr as Array;
				var len : int = _arrPlayer.length;
				for (var i : int = 0 ; i < arrCard.length * len ; i++ ) {
					var obplayer : PlayerObject =  _arrPlayer[i % len];
					var nplayer : String = obplayer.displayName;
					var numChia : int = Math.floor(i / len);
					var _C : Card =  (nplayer == Main.getInstance().currPlayer.displayName) ? new Card(arrCard[numChia]) : new Card(); 
					var pos : int = getPositionPlayer(nplayer);
					obplayer.arrCard.push(_C);
					_C.visible = false;
					_C.x = 498; _C.y = 274;
					_C.width = 50;
					_C.height = 67;
					card_mc.addChild(_C);
					var _scaleX : Number = (pos == 0) ? currCardScaleX : cardDuoiBanScaleX;
					var _scaleY : Number = (pos == 0) ? currCardScaleY : cardDuoiBanScaleY;
					arrChiaBai.push( { _card : _C, numChia : numChia , pos : pos, _scaleX: _scaleX, _scaleY: _scaleY} );
				}
				tChiaBai = new Timer(20, arrCard.length * _arrPlayer.length);
				tChiaBai.addEventListener(TimerEvent.TIMER, chia);
				var cs : int = 0;
				tChiaBai.start();
				
			}catch (err : Error) { Cc.error(err + " dealCard") }
			function chia(e : TimerEvent) : void {
				try {
					var C: Card = arrChiaBai[cs]._card;
					var num : int = arrChiaBai[cs].numChia;
					C.visible = true;
					//Sound.play(TypeSounds.SOUND_ADD);
					TweenMax.to(C, 0.2, { x : arrCardPoint[arrChiaBai[cs].pos].x + arrChiaBai[cs].numChia * direction[arrChiaBai[cs].pos].x, y : arrCardPoint[arrChiaBai[cs].pos].y + arrChiaBai[cs].numChia * direction[arrChiaBai[cs].pos].y, scaleX : arrChiaBai[cs]._scaleX, scaleY: arrChiaBai[cs]._scaleY, onComplete : Delegate.create(chiaBaiComplete, obj.NName, num, C) } );
				}catch (er : Error) { Cc.error("gameBoard.chia : " + er) }
				cs++;
			}
		}
		private function chiaBaiComplete(_n : String, num : int, C : Card) : void {
			
			if (C.number > 0) {
				C.ready = true;
				C.addEventListener(Card.PICK_CARD, pickCard);
				C.addEventListener(Card.CHECKING, checkTargetDrag);
				C.addEventListener(Card.DROP_CARD, dropCard);
			}
			if (num == 12 && C.number > 0) {
				finishChia = true;
				xepbai_btn.visible = true;
				bochon_btn.visible = true;
				danhbai_btn.visible = true;
				boluot_btn.visible = true;
				Util.adjustButton(danhbai_btn, true);
				Util.adjustButton(boluot_btn, true);
				Util.adjustButton(bochon_btn, true);
				
				turnOfPlayer = _n;
			}
		}
		
		private function pickCard(e : Event) : void {
			if (!finishChia) return;
			var _card : Card = Card(e.currentTarget);
			_card.startDrag();
			card_mc.setChildIndex(_card, card_mc.numChildren - 1);
		}
		
		private function checkTargetDrag(e : DataEvent) : void {
			try {
				if (!finishChia) return;
				var arr : Array = JSON.decode(e.data);
				var _x : Number = arr[0], _y : Number = arr[1], _startX : Number = arr[2], _startY : Number = arr[3];
				var C : Card = e.currentTarget as Card;
				
				if (targetCard != null) targetCard.setTarget(false);
				for each(var _card : Card in Main.getInstance().currPlayer.arrCard) {
					if (_card.number == C.number) continue;
					if (!C.hitTestObject(_card)) continue;
					if (Math.abs(_card.x - C.x) < direction[0].x && Math.abs(_card.y - C.y) < 10) {
						targetCard = _card;
						targetCard.setTarget(true);
						break;
					}
				}
			}catch(err :Error){Cc.error("checkTargetDrag" + err)}
		}
		
		private function dropCard(e : DataEvent) : void {
			try {
				if (!finishChia) return;
				if (targetCard != null) targetCard.setTarget(false);
				
				var arr : Array = JSON.decode(e.data);
				var _x : Number = arr[0], _y : Number = arr[1], _startX : Number = arr[2], _startY : Number = arr[3];
				var C : Card = e.currentTarget as Card;
				var b : Boolean = false;
				for each(var _card : Card in Main.getInstance().currPlayer.arrCard) {
					if (_card.number == C.number) continue;
					if (!C.hitTestObject(_card)) continue;
					if (Math.abs(_card.x - C.x) < direction[0].x && Math.abs(_card.y - C.y) < 10) {
						var __x : Number = _card.x, __y : Number = _card.y;
						_card.x = _startX; _card.y = _startY;
						C.x = __x; C.y = __y;
						swapItems(Main.getInstance().currPlayer.arrCard, C, _card);
						b = true;
						break;
					}
				}
				if (!b) {
					C.x = _startX; C.y = _startY;
					C.setChoose();
				}
				for (var i : int = 0; i <  Main.getInstance().currPlayer.arrCard.length; i++ ) {
					card_mc.setChildIndex( Main.getInstance().currPlayer.arrCard[i], i);
				}
				
			}catch(err: Error){Cc.error(err + " dropcard")}
		}
		
		private function swapItems(array:Array, item1:*, item2:*) : void{
		   var item1pos:int = array.indexOf(item1);
		   var item2pos:int = array.indexOf(item2);
		   
		   if ((item1pos != -1) && (item2pos != -1))
		   {
			  var tempItem:* = array[item2pos];
			  array[item2pos] = array[item1pos];
			  array[item1pos] = tempItem;
		   }
		}
		
		public function viewToJoin() : void {
			try {
				ready_btn.visible = true;
				_arrPlayer.push(Main.getInstance().currPlayer);
				var j : int = player_mc.numChildren;
				for (var i : int = 0 ; i < j ; i++ ) {
					var _av : avatar = avatar(player_mc.getChildAt(i));
					_av.updatePosition(getPositionPlayer(_av.playerName));
				}
				var _avt : avatar = new avatar(0, Main.getInstance().currPlayer.displayName, Main.getInstance().currPlayer.vip, Main.getInstance().currPlayer.mark);
				player_mc.addChild(_avt);
				
			}catch(err:  Error){Cc.error(err + " viewtojoin")}
		}
		
		private function getAvatarByName(_name : String) : avatar {
			var j : int = player_mc.numChildren;
			for (var i : int = 0 ; i < j; i++ ) {
				var _avt : avatar = avatar(player_mc.getChildAt(i));
				if (_avt.playerName == _name) return _avt;
			}
			return null;
		}
		public function otherLeave(_name : String) : void {
			var pl : PlayerObject = getPlayerbyName(_name);
			
			for (var i : int = 0 ; i < _arrPlayer.length; i++ ) {
				if ((_arrPlayer[i] as PlayerObject).displayName == _name) {
					_arrPlayer.splice(i, 1);
					break;
				}
			}
			
			var avt : avatar = getAvatarByName(_name);
			if (avt) {
				avt.removeEvent();
				player_mc.removeChild(avt);
				avt = null;
			}
		}
		public function playerReady(_name : String) : void {
			if (_name == Main.getInstance().currPlayer.displayName) ready_btn.visible = false;
			var _avt : avatar = getAvatarByName(_name);
			if (_avt) _avt.setReady(true);
			var pl : PlayerObject = getPlayerbyName(_name);
			if (pl) pl.ready = true;
			begin_btn.visible = checkBegin();
		}
		
		private function getPlayerbyName(_name : String) : PlayerObject {
			for each(var pl : PlayerObject in _arrPlayer) {
				if (pl.displayName == _name) return pl;
			}
			return null;
		}
		private function checkBegin() : Boolean {
			//Cc.log("isCreat " + isCreate);
			//Cc.log(_arrPlayer.length < 2);
			if (!isCreate) return false;
			if (_arrPlayer.length < 2) return false;
			for each(var pl : PlayerObject in _arrPlayer) {
				//Cc.log(pl);
				if (!pl.ready) return false;
			}
			return true;
		}
		private function addEvent() : void {
			menu.back_btn.addEventListener(MouseEvent.CLICK, sendExit);
			ready_btn.addEventListener(MouseEvent.CLICK, sendReady);
			begin_btn.addEventListener(MouseEvent.CLICK, sendStart);
		}
		
		public function remove() : void {
			removeEvent();
			if (this.parent) this.parent.removeChild(this);
		}
		
		private function removeEvent() : void {
			menu.back_btn.removeEventListener(MouseEvent.CLICK, sendExit);
			ready_btn.removeEventListener(MouseEvent.CLICK, sendReady);
		}
		
		private function sendExit(e  :MouseEvent) : void {
			//if (currentTable.status == 1 && !view) return;
			var leaveRequestPacket:LeaveRequestPacket = new LeaveRequestPacket();
			leaveRequestPacket.tableid = Main.getInstance().gameObject.TABLEID;
			Main.getInstance().socket.send(leaveRequestPacket);	
		}
		
		private function getPositionPlayer(_name : String) : int {
			if (_name == Main.getInstance().currPlayer.displayName) return 0;
			var j : int = 0;
			for (var i : int = 0; i < _arrPlayer.length; i++) {
				if ((_arrPlayer[i] as PlayerObject).displayName ==  Main.getInstance().currPlayer.displayName) {
					j = i;
					break;
				}
			}
			for (var k : int = 0; k < _arrPlayer.length; k++) {
				if (_arrPlayer[k].displayName == _name) {
					if (k < j) return Main.getInstance().config.maxPLayer - j + k;
					if (k > j) return k - j;
				}
			}
			return 0;
		}
		
		public function get tableid():int 
		{
			return _tableid;
		}
		
		public function set tableid(value:int):void 
		{
			_tableid = value;
		}
		
		public function get mark():int 
		{
			return _mark;
		}
		
		public function set mark(value:int):void 
		{
			_mark = value;
		}
		
		public function get arrPlayer():Array 
		{
			return _arrPlayer;
		}
		
		public function set arrPlayer(value:Array):void 
		{
			_arrPlayer = value;
		}
		
		public function get view():Boolean 
		{
			return _view;
		}
		
		//public function set view(value:Boolean):void 
		//{
			//_view = value;
		//}
	}

}